#这个是模拟服务器接口发送和接收
def log(strr):
    # print(strr,end='')
    return None
# print('program starts.')
### log('import files...')
from socket import socket,gethostbyname,gethostname
from json import dumps,loads
from configparser import ConfigParser
from sys import path as spath
from random import randint
# from os import system
# print('done.')

def send(senddata,serverip) :
    # log('getting address...')
    address = (serverip,12345)
    # print('done')
    # print('address=',address)

    # log('making socket...')
    sk=socket()
    # print('done.')

    # log('init code...')
    
    # print('done.')

    # log('init PID...')
    # print('done.')

    # log('summon dict...')
    dic = senddata
    str_dic = dumps(dic)
    # print('done.')

    # log('connecting...')
    sk.connect(address)
    # print('done.')

    # log('sending message to address...')
    sk.send(bytes(str_dic,encoding='utf-8'))
    # print('done')

    # log('closing...')
    sk.close()
    # print('done.')

    # while(1):
    #     ThreadLock.acquire()
    #     # print(JudgeQueue)
    #     ThreadLock.release()
    #     system('cls')
    return None

def accept(port):

    ### log('creating object...')
    sk = socket()
    # print('done.')

    ### log('getting address...')
    address = ('192.168.124.11',int(port))
    # print('done.')
    # print('address=',address)

    ### log('binding...')
    # print(address)
    
    sk.bind(address)
    # print('done.')

    ### log('set listen to 16...')
    sk.listen(16)
    # print('done.')

    # print('listening...')
    
    conn,addr=sk.accept()
    data = conn.recv(4096)
    # print('get message=',data)

    return loads(str(data,encoding='utf-8'))

def randValidPort() :
    while 1:
        port = randint(0,65535)
        sk = socket()
        address = ('',port)
        try :
            sk.bind(address)
            return port
        except OSError:
            continue

def upload(Diction) :
    '''接口:
    code:
    pid:
    ip:
    port:
    '''
    Diction['port'] = randValidPort()
    send(Diction,Diction['ip'])
    return accept(Diction['port'])

if __name__ == '__main__' :
    senddata={
        'code':r'''
        #include<stdioo.h>
        int main(){
            int a,b;
            scanf("%d%d",&a,&b);
            printf("%d",a+b);
            return 0;
        }
        ''',
        'pid':'P1001',
        'ip':'192.168.124.11',
        }
    print(upload(senddata))
